package com.semp.jadoma.admin.action;

import java.io.File;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;

import com.semp.jadoma.admin.form.GalleryObjectAddForm;
import com.semp.jadoma.admin.utils.Config;
import com.semp.jadoma.admin.utils.media.FileSaver;
import com.semp.jadoma.admin.utils.media.Thumbnail;
import com.semp.jadoma.admin.utils.webapp.Forward;
import com.semp.jadoma.core.model.GalleryObject;
import com.semp.jadoma.core.service.GalleryService;

public class GalleryObjectAddAction extends RootAction {

	private final static Logger logger = Logger.getLogger(InitServlet.class);
	
	@Override
	public String executeChild(ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		GalleryObjectAddForm goaForm = (GalleryObjectAddForm) form;
		FormFile formFile = goaForm.getGalleryObject();
		
		// Store file
		File object = FileSaver.save(formFile.getInputStream(), String.valueOf(goaForm.getParentId()));
		logger.debug("Created object " + object.getCanonicalPath());
		//Thumb File
		File thumb = Thumbnail.createThumbnail(object, Config.THUMB_SIZE);
		logger.debug("Created object thumb " + thumb.getCanonicalPath());
		
		//Store object
		GalleryObject galleryObject = new GalleryObject();
		galleryObject.setCreationDate(new Date());
		galleryObject.setExternalId(goaForm.getParentId());
		galleryObject.setName("");
		
		GalleryService.createObject(galleryObject);
		
		return Forward.SUCCESS;
	}

}
